<template>
  <div class="details-container" :class="{ 'preview-mode': isPreviewMode }">
    <div v-if="error" class="error-container">
      <a-alert
          message="组件加载错误"
          :description="error.message"
          type="error"
          show-icon
          closable
      />
    </div>

    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="header-title">
          <div class="title-text">{{ isPreviewMode ? '申请单详情预览' : '申请单详情' }}</div>
          <div class="title-sub">{{ isPreviewMode ? 'REQUEST PREVIEW' : 'REQUEST DETAILS' }}</div>
        </div>
        <div class="header-glow"></div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div v-if="!error" class="main-content">
      <div class="requirement-panel">

        <div class="usecase-panel">
          <div class="department-selector">
            <div class="selector-label">业务部门</div>
            <a-select
                show-search
                placeholder="请输入部门名称搜索"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="onDepartmentSearch"
                @change="(value, _option) => onDepartmentChange(value)"
                class="department-select"
                popupClassName="custom-dropdown"
                :value="selectedDepartment"
                :disabled="isDisabled"
            >
              <a-select-option
                  v-for="department in departmentList"
                  :key="department.id"
                  :value="department.nameCn+'['+department.desc+']'+department.nameEn"
              >
              </a-select-option>
            </a-select>
          </div>

          <div class="role-selector">
            <div class="selector-label">角色</div>
            <a-select
                v-model:value="selectedRole"
                show-search
                placeholder="请输入角色名称搜索"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="onRoleSearch"
                @focus="onRoleFocus"
                @blur="onRoleBlur"
                @change="(value, _option) => onRoleChange(value)"
                class="role-select"
                popupClassName="custom-dropdown"
                :disabled="isDisabled || !selectedDepartment"
                :class="{ 'new-role': isRoleNew }"
            >
              <a-select-option
                  v-for="role in roleList"
                  :key="role.id"
                  :value="role.name"
              >
              </a-select-option>
            </a-select>
          </div>

          <div class="business-selector">
            <div class="selector-label">业务</div>
            <a-select
                v-model:value="selectedBusiness"
                show-search
                placeholder="请输入业务名称搜索"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="onBusinessSearch"
                @focus="onBusinessFocus"
                @blur="onBusinessBlur"
                @change="(value, _option) => onBusinessChange(value)"
                class="business-select"
                popupClassName="custom-dropdown"
                :disabled="isDisabled || !inputRole"
                :class="{ 'new-business': isBusinessNew }"
            >
              <a-select-option
                  v-for="business in businessList"
                  :key="business.id"
                  :value="business.name"
              >
              </a-select-option>
            </a-select>
          </div>
        </div>

        <div class="failMode-panel">
          <div class="panel-title">痛点</div>
          <div class="failMode-list">
            <div v-for="(failMode, index) in failModes" :key="index" class="failMode-item">
              <div class="failMode-header" @click="!isDisabled && toggleFailMode(index)">
                <div class="failMode-expand-icon">
                  <RightOutlined :class="{ 'expanded': failMode.isExpanded }" />
                </div>
                <a-input
                    v-model:value="failMode.modeDesc"
                    placeholder="请输入痛点描述"
                    type="text"
                    :auto-size="{ minRows: 2, maxRows: 5 }"
                    class="failMode-input"
                    @blur="!isDisabled && handleFailModeBlur(index)"
                    :disabled="isDisabled || !inputBusiness"
                    @click.stop
                    :readonly="isDisabled"
                />
                <a-button
                    v-if="!isDisabled && failModes.length > 1"
                    type="text"
                    danger
                    class="delete-btn"
                    @click.stop="removeFailMode(index)"
                >
                  <DeleteOutlined />
                </a-button>
              </div>

              <!-- 控制计划面板 -->
              <div class="ctrlPlan-panel" v-show="failMode.isExpanded">
                <div class="ctrlPlan-header">
                  <span class="ctrlPlan-title">控制计划</span>
                  <a-button
                      v-if="!isDisabled"
                      type="dashed"
                      size="small"
                      @click="addCtrlPlan(index)"
                  >
                    <PlusOutlined />
                    添加控制计划
                  </a-button>
                </div>

                <div class="ctrlPlan-list">
                  <div v-for="(ctrlPlan, ctrlIndex) in failMode.ctrlPlans" :key="ctrlIndex" class="ctrlPlan-item">
                    <div class="ctrlPlan-content">
                      <div class="ctrlPlan-field-spec">
                        <div class="field-label">控制要求</div>
                        <a-input
                            v-model:value="ctrlPlan.spec"
                            placeholder="请输入控制要求"
                            class="ctrlPlan-input"
                            :disabled="isDisabled || !inputBusiness"
                            :readonly="isDisabled"
                        />
                      </div>
                      <div class="ctrlPlan-field-capacity">
                        <div class="field-label">容量</div>
                        <a-select
                            v-model:value="ctrlPlan.capacityDisplay"
                            show-search
                            placeholder="请输入容量名称搜索"
                            :filter-option="false"
                            :not-found-content="fetching ? undefined : null"
                            @search="(value) => !isDisabled && onCapacitySearch(value, index, ctrlIndex)"
                            @focus="() => !isDisabled && onCapacityFocus(index, ctrlIndex)"
                            @blur="() => !isDisabled && onCapacityBlur(index, ctrlIndex)"
                            @change="(value) => !isDisabled && onCapacityChange(value, index, ctrlIndex)"
                            class="ctrlPlan-select"
                            :disabled="isDisabled || !inputBusiness"
                            :class="{ 'new-capacity': ctrlPlan.isCapacityNew }"
                            allow-clear
                            popupClassName="custom-dropdown"
                        >
                          <a-select-option
                              v-for="capacity in capacityList"
                              :key="capacity.id"
                              :value="capacity.cnDesc"
                          >
                            {{ capacity.cnDesc }}
                          </a-select-option>
                        </a-select>
                      </div>
                      <div class="ctrlPlan-field-frequency">
                        <div class="field-label">时机</div>
                        <a-select
                            v-model:value="ctrlPlan.frequencyCnList"
                            mode="multiple"
                            placeholder="请选择时机"
                            class="ctrlPlan-select"
                            :disabled="isDisabled || !inputBusiness"
                            popupClassName="custom-dropdown"
                            :show-search="!isPreviewMode"
                            :show-arrow="!isPreviewMode"
                        >
                          <a-select-option
                              v-for="frequency in effectiveFrequencyList"
                              :key="frequency.id"
                              :value="frequency.cnDesc"
                          >
                            {{ frequency.cnDesc }}
                          </a-select-option>
                        </a-select>
                      </div>
                      <div class="ctrlPlan-field-reactionPlan">
                        <div class="field-label">反应计划</div>
                        <a-select
                            v-model:value="ctrlPlan.reactionPlanCnList"
                            mode="multiple"
                            placeholder="请选择反应计划"
                            class="ctrlPlan-select"
                            :disabled="isDisabled || !inputBusiness"
                            popupClassName="custom-dropdown"
                            :show-search="!isPreviewMode"
                            :show-arrow="!isPreviewMode"
                        >
                          <a-select-option
                              v-for="reactionPlan in effectiveReactionPlanList"
                              :key="reactionPlan.id"
                              :value="reactionPlan.cnDesc"
                          >
                            {{ reactionPlan.cnDesc }}
                          </a-select-option>
                        </a-select>
                      </div>
                    </div>

                    <a-button
                        v-if="!isDisabled && failMode.ctrlPlans.length > 1"
                        type="text"
                        danger
                        class="delete-ctrlPlan-btn"
                        @click="removeCtrlPlan(index, ctrlIndex)"
                    >
                      <DeleteOutlined />
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <a-button
              v-if="!isDisabled"
              type="dashed"
              class="add-btn"
              @click="addFailMode"
          >
            <PlusOutlined />
            添加痛点
          </a-button>
        </div>

        <div class="value-box">
          <div class="panel-title">
            价值主张
            <div class="value-actions" v-if="isPreviewMode">
              <a-button
                  v-if="!isEditingValue"
                  type="link"
                  class="edit-value-btn"
                  @click="startEditingValue"
              >
                <EditOutlined />
                编辑
              </a-button>
              <template v-else>
                <a-button
                    type="link"
                    class="save-value-btn"
                    @click="saveValue"
                    :loading="savingValue"
                >
                  <SaveOutlined />
                  保存
                </a-button>
                <a-button
                    type="link"
                    class="cancel-value-btn"
                    @click="cancelEditingValue"
                >
                  <CloseOutlined />
                  取消
                </a-button>
              </template>
            </div>
          </div>
          <a-textarea
              v-model:value="requirementValue"
              placeholder="请输入价值主张描述"
              :auto-size="{ minRows: 3, maxRows: 6 }"
              class="value-input"
              :disabled="(isPreviewMode && !isEditingValue) || (props.mode === 'add' && !inputBusiness)"
              :readonly="isPreviewMode && !isEditingValue"
          />
        </div>

        <div class="btn-panel" v-if="showSaveButton">
          <a-button type="primary" class="save-btn" @click="handleSave" :loading="saving">
            <SaveOutlined />
            保存
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.error-container {
  margin: 16px;
  border-radius: 8px;
  overflow: hidden;
}
.details-container {
  height: 100%;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;

  .header {
    height: calc(100% / 6);
    background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 50%, #6366f1 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(14, 165, 233, 0.3);
  }

  .header::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url("/akitorSys.svg");
    background-size: cover;
    opacity: 0.3;
  }

  .header-content {
    position: relative;
    z-index: 2;
    text-align: center;
  }

  .header-title {
    color: white;
  }

  .title-text {
    font-size: 28px;
    font-weight: 700;
    letter-spacing: 1px;
    margin-bottom: 5px;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  }

  .title-sub {
    font-size: 14px;
    opacity: 0.9;
    letter-spacing: 2px;
    font-weight: 300;
  }

  .header-glow {
    position: absolute;
    width: 200px;
    height: 200px;
    background: radial-gradient(circle, rgba(59, 130, 246, 0.4) 0%, rgba(59, 130, 246, 0) 70%);
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
  }
}

.main-content {
  padding: 24px;
  margin: 0 auto;
}

.selector-label {
  color: #e2e8f0;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  letter-spacing: 1px;
}

/* 通用下拉框样式 */
::v-deep(.ant-select-selector) {
  background: rgba(15, 23, 42, 0.7) !important;
  border: 1px solid #334155 !important;
  border-radius: 8px !important;
  color: #f1f5f9 !important;
  transition: all 0.3s ease;
}

::v-deep(.ant-select-selector:hover) {
  border-color: #3b82f6 !important;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2) !important;
}

.usecase-panel {
  display: flex;
  margin-bottom: 24px;

  .department-selector {
    margin-right: 24px;
    flex: 2;
    .department-select {
      width: 100%;
    }
  }
  .role-selector {
    margin-right: 24px;
    flex: 1;
    .role-select {
      width: 100%;
    }
  }
  .business-selector {
    flex: 1;
    .business-select {
      width: 100%;
    }
  }

  ::v-deep(.new-role .ant-select-selector) {
    background: rgba(234, 179, 8, 0.1) !important;
    border: 1px solid #eab308 !important;
    box-shadow: 0 0 0 2px rgba(234, 179, 8, 0.2) !important;
  }

  ::v-deep(.new-role .ant-select-selection-item) {
    color: #fef08a !important;
  }

  ::v-deep(.new-business .ant-select-selector) {
    background: rgba(234, 179, 8, 0.1) !important;
    border: 1px solid #eab308 !important;
    box-shadow: 0 0 0 2px rgba(234, 179, 8, 0.2) !important;
  }

  ::v-deep(.new-business .ant-select-selection-item) {
    color: #fef08a !important;
  }
}

::v-deep(.ant-select-arrow) {
  color: #64748b;
}

::v-deep(.ant-select-selection-placeholder) {
  color: #808385 !important;
}

::v-deep(.ant-select-open .ant-select-selection-item) {
  color: #808385 !important;
}

::v-deep(.ant-input)::-webkit-input-placeholder {
  color: #808385 !important;
  opacity: 0.7;
}

.btn-panel {
  display: flex;

  .save-btn {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    height: 40px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    gap: 6px;
    border: none;
    position: relative;
    overflow: hidden;
  }

  .save-btn {
    background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(14, 165, 233, 0.4);
  }

  .save-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: 0.5s;
  }

  .save-btn:hover::before {
    left: 100%;
  }

  .save-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(14, 165, 233, 0.6);
  }
}

.failMode-panel {
  margin-bottom: 24px;
  background: rgba(15, 23, 42, 0.6);
  border: 1px solid rgba(51, 65, 85, 0.5);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;

  .panel-title {
    color: #e2e8f0;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    letter-spacing: 1px;
    display: flex;
    align-items: center;
    .value-actions{
      flex: 1;
    }
  }

  .panel-title::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
    border-radius: 2px;
    margin-right: 8px;
  }

  .failMode-item {
    margin-bottom: 16px;
    position: relative;
    padding-bottom: 16px;
    border-bottom: 1px solid rgba(51, 65, 85, 0.5);
  }

  .failMode-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }

  .failMode-header {
    display: flex;
    margin-bottom: 0;
    align-items: flex-start;
    cursor: pointer;
    padding: 8px;
    border-radius: 8px;
    transition: all 0.3s ease;
  }

  .failMode-header:hover {
    background: rgba(59, 130, 246, 0.1);
  }

  .failMode-expand-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 32px;
    margin-right: 8px;
    color: #64748b;
    transition: all 0.3s ease;
  }

  .failMode-expand-icon .expanded {
    transform: rotate(90deg);
  }

  .failMode-input {
    flex: 1;
    background: rgba(15, 23, 42, 0.7) !important;
    border: 1px solid #334155 !important;
    border-radius: 8px !important;
    color: #f1f5f9 !important;
    transition: all 0.3s ease;
    margin-right: 10px;
  }

  .delete-btn {
    margin-top: 4px;
    flex-shrink: 0;
    background: rgba(239, 68, 68, 0.1) !important;
    border: 1px solid rgba(239, 68, 68, 0.3) !important;
    border-radius: 6px !important;
    color: #ef4444 !important;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
  }

  .delete-btn:hover {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: #ef4444 !important;
    transform: scale(1.05);
  }

  .failMode-item::before {
    content: '●';
    position: absolute;
    left: -20px;
    top: 12px;
    color: #3b82f6;
    font-size: 12px;
    opacity: 0.7;
  }

  .add-btn {
    width: 100%;
    border-radius: 8px;
    border-style: dashed;
    border-color: #3b82f6;
    background: rgba(59, 130, 246, 0.1);
    color: #3b82f6;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;
    font-weight: 500;
    position: relative;
    overflow: hidden;
  }

  .add-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.2), transparent);
    transition: 0.5s;
  }

  .add-btn:hover::before {
    left: 100%;
  }

  .add-btn:hover {
    border-color: #0ea5e9;
    color: #0ea5e9;
    background: rgba(14, 165, 233, 0.15);
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3);
  }
}

.failMode-panel:hover {
  border-color: rgba(59, 130, 246, 0.3);
  box-shadow: 0 6px 25px rgba(14, 165, 233, 0.15);
}

.ctrlPlan-panel {
  background: rgba(30, 41, 59, 0.5);
  border-radius: 8px;
  padding: 16px;
  margin-top: 12px;
  border: 1px solid rgba(51, 65, 85, 0.3);
  animation: slideDown 0.3s ease;

  /* 新容量标记样式 */
  ::v-deep(.new-capacity .ant-select-selector) {
    background: rgba(234, 179, 8, 0.1) !important;
    border: 1px solid #eab308 !important;
    box-shadow: 0 0 0 2px rgba(234, 179, 8, 0.2) !important;
  }

  ::v-deep(.new-capacity .ant-select-selection-item) {
    color: #fef08a !important;
  }

  .ctrlPlan-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .ctrlPlan-title {
    color: #e2e8f0;
    font-size: 14px;
    font-weight: 600;
  }

  .ctrlPlan-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .ctrlPlan-item {
    display: flex;
    flex-direction: row;
    gap: 12px;

    .ctrlPlan-content {
      min-width: 90%;
      display: flex;
      flex-direction: row;
      gap: 12px;

      .ctrlPlan-field-spec {
        flex: 4;
      }
      .ctrlPlan-field-capacity {
        flex: 1;
      }
      .ctrlPlan-field-frequency {
        flex: 1;
      }
      .ctrlPlan-field-reactionPlan {
        flex: 2;
      }
      .field-label {
        color: #cbd5e1;
        font-size: 12px;
        margin-bottom: 4px;
        font-weight: 500;
      }

      .ctrlPlan-input, .ctrlPlan-select {
        width: 100%;
      }
    }

    .delete-ctrlPlan-btn {
      flex-shrink: 0;
      background: rgba(239, 68, 68, 0.1) !important;
      border: 1px solid rgba(239, 68, 68, 0.3) !important;
      border-radius: 6px !important;
      color: #ef4444 !important;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      margin-top: 28px;
    }

    .delete-ctrlPlan-btn:hover {
      background: rgba(239, 68, 68, 0.2) !important;
      border-color: #ef4444 !important;
      transform: scale(1.05);
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.value-box {
  margin-bottom: 24px;
  background: rgba(15, 23, 42, 0.6);
  border: 1px solid rgba(51, 65, 85, 0.5);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;

  .panel-title {
    color: #e2e8f0;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    letter-spacing: 1px;
    display: flex;
    align-items: center;

    .value-actions {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 8px;
      justify-content: right;

      .edit-value-btn,
      .save-value-btn,
      .cancel-value-btn {
        padding: 0;
        height: auto;
        font-size: 12px;
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .edit-value-btn {
        color: #3b82f6;
      }

      .save-value-btn {
        color: #10b981;
      }

      .cancel-value-btn {
        color: #ef4444;
      }

      .edit-value-btn:hover,
      .save-value-btn:hover,
      .cancel-value-btn:hover {
        opacity: 0.8;
      }
    }
  }

  .panel-title::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
    border-radius: 2px;
    margin-right: 8px;
  }

  .value-input {
    background: rgba(15, 23, 42, 0.7) !important;
    border: 1px solid #334155 !important;
    border-radius: 8px !important;
    color: #f1f5f9 !important;
    transition: all 0.3s ease;
  }

  .value-input:hover {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2) !important;
  }
}

.value-box:hover {
  border-color: rgba(59, 130, 246, 0.3);
  box-shadow: 0 6px 25px rgba(14, 165, 233, 0.15);
}

/* 全局样式覆盖 */
::v-deep(.ant-input) {
  background: rgba(15, 23, 42, 0.7) !important;
  border: 1px solid #334155 !important;
  border-radius: 8px !important;
  color: #f1f5f9 !important;
}

::v-deep(.ant-input:hover) {
  border-color: #3b82f6 !important;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2) !important;
}

::v-deep(.ant-input:focus) {
  border-color: #3b82f6 !important;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2) !important;
}

::v-deep(.ant-select-dropdown) {
  background: #1e293b !important;
  border: 1px solid #334155 !important;
}

::v-deep(.ant-select-item) {
  color: #f1f5f9 !important;
}

::v-deep(.ant-btn-dashed) {
  border-color: #3b82f6 !important;
  color: #3b82f6 !important;
  background: rgba(59, 130, 246, 0.1) !important;
}

::v-deep(.ant-btn-dashed:hover) {
  border-color: #0ea5e9 !important;
  color: #0ea5e9 !important;
  background: rgba(14, 165, 233, 0.15) !important;
}

.preview-mode{
  .usecase-panel,
  .failMode-panel,
  .value-box {
    opacity: 0.9;
  }

  .failMode-header {
    cursor: default !important;
  }

  .failMode-header:hover {
    background: transparent !important;
  }

  /* 确保预览模式下所有交互元素都被禁用 */
  ::v-deep(.ant-input[disabled]),
  ::v-deep(.ant-select-disabled .ant-select-selector),
  ::v-deep(.ant-btn[disabled]) {
    background: rgba(30, 41, 59, 0.3) !important;
    border-color: #475569 !important;
    color: #cbd5e1 !important;
    cursor: default !important;
    opacity: 1 !important;
  }

  ::v-deep(.ant-input[disabled]) {
    color: #e2e8f0 !important;
    background: rgba(30, 41, 59, 0.5) !important;
    border-color: #475569 !important;
    opacity: 1 !important;
  }

  ::v-deep(.ant-select-arrow) {
    display: none;
  }

  ::v-deep(.delete-btn),
  ::v-deep(.delete-ctrlPlan-btn),
  ::v-deep(.add-btn) {
    display: none !important;
  }

  /* 多选标签样式 - 重点修复 */
  ::v-deep(.ant-select-multiple .ant-select-selection-item) {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.4) 0%, rgba(99, 102, 241, 0.3) 100%) !important;
    border: 1px solid rgba(99, 102, 241, 0.6) !important;
    color: #f1f5f9 !important;
    border-radius: 6px !important;
    padding: 2px 8px !important;
    height: 26px !important;
    line-height: 22px !important;
    font-size: 12px !important;
    margin: 2px 4px 2px 0 !important;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
  }

  ::v-deep(.ant-select-multiple.ant-select-disabled .ant-select-selection-item) {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.3) 0%, rgba(99, 102, 241, 0.2) 100%) !important;
    border: 1px solid rgba(99, 102, 241, 0.4) !important;
    color: #e2e8f0 !important;
  }

  ::v-deep(.ant-select-disabled .ant-select-selection-placeholder) {
    color: #64748b !important;
  }

  /* 隐藏所有交互图标 */
  ::v-deep(.ant-select-arrow),
  ::v-deep(.ant-select-clear),
  ::v-deep(.ant-input-suffix),
  ::v-deep(.ant-input-prefix) {
    display: none !important;
  }
}
</style>

<script setup lang="ts">
import {computed, nextTick, onErrorCaptured, onMounted, ref, watch} from 'vue'
import {Button, Input, message, Select, Textarea,Alert} from 'ant-design-vue'
import api from "@/utils/api";
import {DeleteOutlined, PlusOutlined, RightOutlined, SaveOutlined, EditOutlined, CloseOutlined} from "@ant-design/icons-vue";

const ASelect = Select;
const ASelectOption = Select.Option;
const AButton = Button;
const AInput = Input;
const ATextarea = Textarea;
const AAlert = Alert;

const error = ref();

onErrorCaptured((err, instance, info) => {
  console.error('组件错误:', err);
  console.error('错误信息:', info);
  console.error('错误instance:', instance);
  error.value = err;

  return false; // 阻止错误继续向上传播
});

interface Props {
  mode?: 'add' | 'preview';
  previewData?: any;
  loading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  mode: 'add',
  loading: false
});

const previewBasicInfo = ref({
  dpmNameCn: '',
  roleName: '',
  businessName: '',
  createDate: ''
});

// 预览数据填充逻辑
watch(
    () => props.previewData,
    (newData) => {
      if (props.mode === 'preview' && newData) {
        console.log('检测到预览数据变化，准备填充', newData);
        nextTick(() => {
          fillPreviewData(newData);
        });
      }
    },
    {
      immediate: true,
      deep: true
    }
);

// 预览数据填充函数
const fillPreviewData = (data: any) => {
  try {
    console.log('开始填充预览数据:', data);

    // 重置所有数据
    resetAllData();

    if (data && typeof data === 'object') {
      // 填充基础信息
      fillBasicInfo(data);

      // 填充部门、角色、业务信息
      fillUseCaseInfo(data);

      // 填充价值主张
      fillValueInfo(data);

      // 填充失效模式和控制计划
      fillFailModesAndCtrlPlans(data);
    } else {
      console.warn('预览数据格式不正确:', data);
      setDefaultData();
    }

    console.log('预览数据填充完成');
  } catch (error) {
    console.error('填充预览数据时发生严重错误:', error);
    setErrorData();
  }
};

// 重置所有数据
const resetAllData = () => {
  selectedDepartment.value = '';
  selectedRole.value = '';
  selectedBusiness.value = '';
  requirementValue.value = '';
  failModes.value = [];
  requirementId.value = null;
  previewBasicInfo.value = {
    dpmNameCn: '',
    roleName: '',
    businessName: '',
    createDate: ''
  };
};

// 填充基础信息
const fillBasicInfo = (data: any) => {
  previewBasicInfo.value = {
    dpmNameCn: data.dpmNameCn || '',
    roleName: data.roleName || '',
    businessName: data.businessName || '',
    createDate: data.createDate || ''
  };
};

// 填充用例信息
const fillUseCaseInfo = (data: any) => {
  if (data.dpmNameCn && typeof data.dpmNameCn === 'string') {
    selectedDepartment.value = data.dpmNameCn;
  }
  if (data.roleName && typeof data.roleName === 'string') {
    selectedRole.value = data.roleName;
  }
  if (data.businessName && typeof data.businessName === 'string') {
    selectedBusiness.value = data.businessName;
  }
};

// 填充价值主张信息
const fillValueInfo = (data: any) => {
  if (data.value && typeof data.value === 'string') {
    requirementValue.value = data.value;
    originalValue.value = data.value;
  }
  if (data.id && typeof data.id === 'number') {
    requirementId.value = data.id;
  }
};

// 填充失效模式和控制计划
const fillFailModesAndCtrlPlans = (data: any) => {
  const safeFailModes: FailMode[] = [];

  // 优先使用嵌套的失效模式列表
  if (data.dtoFailMode4requirementList && Array.isArray(data.dtoFailMode4requirementList)) {
    data.dtoFailMode4requirementList.forEach((fm: any) => {
      try {
        const failMode: FailMode = {
          modeDesc: fm.fmDesc || '',
          ctrlPlans: [],
          isExpanded: true
        };

        // 处理控制计划数据
        if (fm.ctrlPlans && Array.isArray(fm.ctrlPlans)) {
          fm.ctrlPlans.forEach((cp: any) => {
            const ctrlPlan = createCtrlPlanFromData(cp);
            failMode.ctrlPlans.push(ctrlPlan);
          });
        }

        // 如果没有控制计划，添加一个空的
        if (failMode.ctrlPlans.length === 0) {
          failMode.ctrlPlans.push(createEmptyCtrlPlan());
        }

        safeFailModes.push(failMode);
      } catch (fmError) {
        console.error('处理失效模式时出错:', fmError, fm);
        safeFailModes.push(createErrorFailMode(fm.fmDesc));
      }
    });
  }
  // 如果没有嵌套数据，尝试使用平级字段创建单个失效模式
  else if (data.fmDesc) {
    const failMode: FailMode = {
      modeDesc: data.fmDesc || '',
      ctrlPlans: [createCtrlPlanFromData(data)],
      isExpanded: true
    };
    safeFailModes.push(failMode);
  }
  // 如果都没有数据，创建默认的
  else {
    safeFailModes.push(createDefaultFailMode());
  }

  failModes.value = safeFailModes;
};

// 从数据创建控制计划
const createCtrlPlanFromData = (cp: any): CtrlPlan => {
  return {
    spec: cp.cpSpec || '',
    capacityDisplay: cp.capacityCn || '',
    frequencyCnList: extractFrequencyList(cp),
    reactionPlanCnList: extractReactionPlanList(cp),
    capacityId: cp.capacityId,
    isCapacityNew: false
  };
};

// 提取频率列表
const extractFrequencyList = (cp: any): string[] => {
  if (cp.frequencyList && typeof cp.frequencyList === 'object') {
    return Object.values(cp.frequencyList).filter((freq: any) =>
        freq && typeof freq === 'string'
    ) as string[];
  } else if (cp.frequencyCnList && Array.isArray(cp.frequencyCnList)) {
    return cp.frequencyCnList.filter((freq: any) =>
        freq && typeof freq === 'string'
    );
  } else if (cp.frequencyCn && typeof cp.frequencyCn === 'string') {
    return [cp.frequencyCn];
  }
  return [];
};

// 提取反应计划列表
const extractReactionPlanList = (cp: any): string[] => {
  if (cp.reactionPlanList && typeof cp.reactionPlanList === 'object') {
    return Object.values(cp.reactionPlanList).filter((plan: any) =>
        plan && typeof plan === 'string'
    ) as string[];
  } else if (cp.reactionPlanCnList && Array.isArray(cp.reactionPlanCnList)) {
    return cp.reactionPlanCnList.filter((plan: any) =>
        plan && typeof plan === 'string'
    );
  } else if (cp.reactionPlanCn && typeof cp.reactionPlanCn === 'string') {
    return [cp.reactionPlanCn];
  }
  return [];
};

// 创建空的【控制计划】
const createEmptyCtrlPlan = (): CtrlPlan => ({
  spec: '',
  capacityDisplay: '',
  frequencyCnList: [],
  reactionPlanCnList: [],
  capacityId: undefined,
  isCapacityNew: false
});

// 创建错误失效模式
const createErrorFailMode = (fmDesc: string): FailMode => ({
  modeDesc: fmDesc || '数据加载异常',
  ctrlPlans: [createEmptyCtrlPlan()],
  isExpanded: true
});

// 创建默认失效模式
const createDefaultFailMode = (): FailMode => ({
  modeDesc: '暂无痛点数据',
  ctrlPlans: [createEmptyCtrlPlan()],
  isExpanded: true
});

// 设置错误数据
const setErrorData = () => {
  failModes.value = [{
    modeDesc: '数据加载失败',
    ctrlPlans: [{
      spec: '请检查数据格式或网络连接',
      capacityDisplay: '',
      frequencyCnList: [],
      reactionPlanCnList: [],
      capacityId: undefined,
      isCapacityNew: false
    }],
    isExpanded: true
  }];
};

// 设置默认数据
const setDefaultData = () => {
  failModes.value = [{
    modeDesc: '数据格式异常',
    ctrlPlans: [createEmptyCtrlPlan()],
    isExpanded: true
  }];
};

const isPreviewMode = computed(() => props.mode === 'preview');
const showSaveButton = computed(() => props.mode === 'add');
const isDisabled = computed(() => {
  return props.mode === 'preview';
});

interface Department {
  id: number;
  nameCn: string;
  nameEn: string;
  desc: string;
  createDate: string;
  updateDate: string;
  createUser: string;
  updateUser: string;
}

interface Role {
  id: number;
  name: string;
  createDate: string;
  updateDate: string;
  createUser: string;
  updateUser: string;
}

interface Business {
  id: number;
  name: string;
  createDate: string;
  updateDate: string;
  createUser: string;
  updateUser: string;
}

interface Capacity {
  id: number;
  cnDesc: string;
  enDesc: string;
}

interface Frequency {
  id: number;
  cnDesc: string;
  enDesc: string;
}

interface ReactionPlan {
  id: number;
  cnDesc: string;
  enDesc: string;
}

interface CtrlPlan {
  spec: string;
  capacityId?: number;
  frequencyCnList: string[];
  reactionPlanCnList: string[];
  capacityDisplay?: string; // 用于显示容量名称
  isCapacityNew?: boolean;
  capacityInput?: string;   // 用于存储新容量的输入值
}

interface FailMode {
  modeDesc: string;
  ctrlPlans: CtrlPlan[];
  isExpanded: boolean; // 新增：控制是否展开
}


const isEditingValue = ref(false);
const savingValue = ref(false);
const saving = ref(false);
const requirementId = ref<number | null>(null);
const originalValue = ref<string>('');

const selectedRole = ref<string>()
const inputRole = ref<string>()
const roleList = ref<Role[]>([])
const isRoleNew = computed(() => {
  if(inputRole.value){
    return !roleList.value.some(role => role.name === inputRole.value)
  }
  if(selectedRole.value){
    return !roleList.value.some(role => role.name === selectedRole.value)
  }
  return false
})

const selectedBusinessDto = ref<any>()
const selectedBusiness = ref<string>()
const inputBusiness = ref<string>()
const businessList = ref<Business[]>([])
const isBusinessNew = computed(() => {
  if(inputBusiness.value){
    return !businessList.value.some(business => business.name === inputBusiness.value)
  }
  if(selectedBusiness.value){
    return !businessList.value.some(business => business.name === selectedBusiness.value)
  }
  return false
})

const selectedDepartment = ref<string>()
const selectedDept = ref<any>()
const selectedRoleObj = ref<any>()
const departmentList = ref<Department[]>([])
const fetching = ref(false)

// 新增数据结构
const capacityList = ref<Capacity[]>([])
const frequencyList = ref<Frequency[]>([])
const reactionPlanList = ref<ReactionPlan[]>([])
const requirementValue = ref<string>('')

const failModes = ref<FailMode[]>([{
  modeDesc: '',
  ctrlPlans: [{
    spec: '',
    capacityId: 2,
    frequencyCnList: [],
    reactionPlanCnList: [],
    capacityDisplay: '一次',
    isCapacityNew: false,
    capacityInput: undefined
  }],
  isExpanded: false
}]);


const startEditingValue = () => {
  originalValue.value = requirementValue.value;
  isEditingValue.value = true;
};

const cancelEditingValue = () => {
  requirementValue.value = originalValue.value;
  isEditingValue.value = false;
};

const saveValue = async () => {
  if (!requirementId.value) {
    message.error('无法保存：缺少申请单ID');
    return;
  }

  try {
    savingValue.value = true;

    const updateData = {
      id: requirementId.value,
      value: requirementValue.value
    };

    console.log('更新价值主张数据:', updateData);

    await api.put('/requirement', updateData);

    message.success('价值主张更新成功');
    isEditingValue.value = false;
    originalValue.value = requirementValue.value;
  } catch (error) {
    console.error('更新价值主张失败:', error);
    message.error('更新失败，请重试');
  } finally {
    savingValue.value = false;
  }
};

// 切换痛点展开/折叠状态
const toggleFailMode = (index: number) => {
  if (failModes.value && failModes.value[index]) {
    failModes.value[index].isExpanded = !failModes.value[index].isExpanded;
  }
};

// 部门搜索
const onDepartmentSearch = (value: string) => {
  fetchDepartments(value)
}
const onRoleSearch = (value: string) => {
  fetchRoles(value)
  if(value){
    inputRole.value=value
  }
}
const onBusinessSearch = (value: string) => {
  fetchBusinesses(value)
  if(value){
    inputBusiness.value=value
  }
}

const onRoleFocus = () => {
  if (!selectedDepartment.value) {
    message.warning('请先选择业务部门')
    return
  }

  // 如果角色列表为空，或者想要每次都重新查询，可以调用空搜索
  if (roleList.value.length === 0) {
    fetchRoles('')
  }
}

const onBusinessFocus = () => {
  if (!selectedRole.value) {
    message.warning('请先选择角色')
    return
  }

  // 如果业务列表为空，或者想要每次都重新查询，可以调用空搜索
  if (businessList.value.length === 0) {
    fetchBusinesses('')
  }
}

const onRoleBlur = () => {
  // 检查当前输入的角色是否是新角色
  if(isRoleNew.value){
    selectedRole.value=inputRole.value
  }
}

const onBusinessBlur = () => {
  // 检查当前输入的业务是否是新业务
  if(isBusinessNew.value){
    selectedBusiness.value=inputBusiness.value
  }
}

// 获取部门列表
const fetchDepartments = async (keyword: string) => {
  try {
    fetching.value = true
    const response = await api.get('/department', { params: { nameCn: keyword } });
    departmentList.value = response.data
  } catch (error) {
    message.error('获取部门列表失败')
    console.error('获取部门列表失败:', error)
  } finally {
    fetching.value = false
  }
}

const fetchRoles = async (keyword: string) => {
  try {
    fetching.value = true
    const response = await api.get('/role/dtoDepartmentRole', {
      params: {
        dpmNameCn:selectedDepartment.value,
        name: keyword
      } });
    roleList.value = response.data
  } catch (error) {
    message.error('获取角色列表失败')
    console.error('获取角色列表失败:', error)
  } finally {
    fetching.value = false
  }
}

const fetchBusinesses = async (keyword: string) => {
  try {
    fetching.value = true
    const response = await api.get('/business/dtoRoleCase', {
      params: {
        roleName: selectedRole.value,
        name: keyword
      } });
    businessList.value = response.data
  } catch (error) {
    message.error('获取业务列表失败')
    console.error('获取业务列表失败:', error)
  } finally {
    fetching.value = false
  }
}

// 获取控制计划相关选项
const fetchCtrlPlanOptions = async () => {
  try {
    fetching.value = true;

    // 获取时机选项
    const frequencyResponse = await api.get('ctrlPlan/cpFrequency');
    frequencyList.value = frequencyResponse.data;

    // 获取反应计划选项
    const reactionPlanResponse = await api.get('ctrlPlan/reactionPlan');
    reactionPlanList.value = reactionPlanResponse.data;

    // 获取容量选项
    await fetchCapacities('');

  } catch (error) {
    message.error('获取控制计划选项失败');
    console.error('获取控制计划选项失败:', error);
  } finally {
    fetching.value = false;
  }
};

// 部门选择变化
const onDepartmentChange = (value: any) => {
  selectedDept.value = departmentList.value.find(department =>
      (department.nameCn+'['+department.desc+']'+department.nameEn) === value)
  if(selectedDept.value){
    selectedDepartment.value=selectedDept.value.nameCn
  }
  selectedRole.value = undefined;
  inputRole.value = undefined;
  roleList.value=[];
  selectedBusiness.value = undefined;
  inputBusiness.value = undefined;
  businessList.value=[];
}

const onRoleChange = (value: any) => {
  selectedRoleObj.value = roleList.value.find(role =>
      (role.name) === value)
  inputRole.value=value;
  selectedBusiness.value = undefined;
  inputBusiness.value = undefined;
  selectedBusinessDto.value = undefined;
  businessList.value=[];
}

const onBusinessChange = (value: any) => {
  console.log('选择的业务ID:', value)
  selectedBusinessDto.value = businessList.value.find(business =>
      (business.name) === value)
  console.log('完整的业务信息:', selectedBusinessDto.value)
  inputBusiness.value=value;
}

const handleSave = async () => {
  try {
    if (isPreviewMode.value) return;

    saving.value = true;

    // 验证必填字段
    if (!selectedDepartment.value) {
      message.error('请选择业务部门');
      return;
    }

    if (!selectedRole.value) {
      message.error('请选择角色');
      return;
    }

    if (!selectedBusiness.value) {
      message.error('请选择业务');
      return;
    }

    // 验证痛点
    if (failModes.value.length === 0 || failModes.value.every(fm => !fm.modeDesc.trim())) {
      message.error('请至少填写一个有效的痛点描述');
      return;
    }

    // 验证控制计划
    for (const failMode of failModes.value) {
      for (const ctrlPlan of failMode.ctrlPlans) {
        if (!ctrlPlan.spec.trim()) {
          message.error('请填写所有控制计划的要求');
          return;
        }
      }
    }

    // 处理新角色和业务的创建
    await handleNewRole();
    await handleNewBusiness();
    await handleNewCapacities();

    // 1. 保存需求申请单
    const requirementData = {
      roleCaseId: selectedBusinessDto.value.id,
      value: requirementValue.value
    };

    console.log('保存需求申请单:', requirementData);
    const requirementResponse = await api.post('/requirement', requirementData);
    const requirementId = requirementResponse.data.id;
    console.log('需求申请单保存成功，ID:', requirementId);

    // 2. 保存失效模式并关联
    for (const [failModeIndex, failMode] of failModes.value.entries()) {
      if (failMode.modeDesc.trim()) {
        // 保存失效模式 - 修正：添加 roleCaseId 字段
        const failModeData = {
          roleCaseId: selectedBusinessDto.value.id, // 新增字段
          modeDesc: failMode.modeDesc
        };
        console.log(`保存失效模式 ${failModeIndex + 1}:`, failModeData);
        const failModeResponse = await api.post('/failMode', failModeData);
        const failModeId = failModeResponse.data.id;
        console.log(`失效模式 ${failModeIndex + 1} 保存成功，ID:`, failModeId);

        // 关联失效模式和需求申请单
        const requirementFMData = {
          requirementId: requirementId,
          failModeId: failModeId
        };
        console.log(`关联失效模式 ${failModeIndex + 1} 和需求申请单:`, requirementFMData);
        await api.post('/failMode/bindRequirement', requirementFMData);

        // 3. 保存控制计划并关联
        for (const [ctrlIndex, ctrlPlan] of failMode.ctrlPlans.entries()) {
          if (ctrlPlan.spec.trim()) {
            // 保存控制计划 - 修正：确保传递 capacityId 字段
            const ctrlPlanData = {
              failModeId: failModeId,
              spec: ctrlPlan.spec,
              capacityId: ctrlPlan.capacityId // 确保这个字段被正确传递
            };
            console.log(`保存控制计划 ${ctrlIndex + 1}:`, ctrlPlanData);
            const ctrlPlanResponse = await api.post('/ctrlPlan', ctrlPlanData);
            const ctrlPlanId = ctrlPlanResponse.data.id;
            console.log(`控制计划 ${ctrlIndex + 1} 保存成功，ID:`, ctrlPlanId);

            // 关联控制计划和需求申请单
            const requirementCPData = {
              requirementId: requirementId,
              ctrlPlanId: ctrlPlanId
            };
            console.log(`关联控制计划 ${ctrlIndex + 1} 和需求申请单:`, requirementCPData);
            await api.post('/ctrlPlan/bindRequirement', requirementCPData);

            // 4. 关联频率
            for (const frequencyCn of ctrlPlan.frequencyCnList) {
              const frequency = frequencyList.value.find(f => f.cnDesc === frequencyCn);
              if (frequency) {
                const frequencyBindData = {
                  ctrlPlanId: ctrlPlanId,
                  frequencyId: frequency.id
                };
                console.log(`关联频率 ${frequencyCn}:`, frequencyBindData);
                await api.post('/cpFrequency/bindCtrlPlan', frequencyBindData);
              }
            }

            // 5. 关联反应计划
            for (const reactionPlanCn of ctrlPlan.reactionPlanCnList) {
              const reactionPlan = reactionPlanList.value.find(r => r.cnDesc === reactionPlanCn);
              if (reactionPlan) {
                const reactionPlanBindData = {
                  ctrlPlanId: ctrlPlanId,
                  reactionPlanId: reactionPlan.id
                };
                console.log(`关联反应计划 ${reactionPlanCn}:`, reactionPlanBindData);
                await api.post('/reactionPlan/bindCtrlPlan', reactionPlanBindData);
              }
            }
          }
        }
      }
    }

    message.success("需求申请单保存成功");

    // 保存成功后重置表单
    resetForm();

  } catch (err) {
    console.error('保存失败:', err);
    message.error('保存失败，请重试');
  } finally {
    saving.value = false;
  }
};

// 重置表单
const resetForm = () => {
  selectedDepartment.value = '';
  selectedRole.value = '';
  selectedBusiness.value = '';
  requirementValue.value = '';
  failModes.value = [{
    modeDesc: '',
    ctrlPlans: [{
      spec: '',
      capacityId: 2,
      frequencyCnList: [],
      reactionPlanCnList: [],
      capacityDisplay: '一次',
      isCapacityNew: false,
      capacityInput: undefined
    }],
    isExpanded: false
  }];
};

const handleNewRole = async () => {
  if (selectedDepartment.value && isRoleNew.value) {
    try {
      fetching.value = true
      await api.post('/role/departmentRole', {
        departmentId: selectedDept.value.id,
        roleName: inputRole.value,
      });
      if(inputRole.value){
        await fetchRoles(inputRole.value);
        selectedRoleObj.value = roleList.value.find(role =>
            (role.name) === inputRole.value)
      }
      message.success("新角色【" + selectedDepartment.value + ":" + inputRole.value + "】创建成功");
    } catch (error) {
      message.error('创建角色失败')
      console.error('创建角色失败:', error)
    } finally {
      fetching.value = false
    }
  }
};

const handleNewBusiness = async () => {
  if (selectedRole.value && isBusinessNew.value) {
    try {
      fetching.value = true
      await api.post('/business/roleBusiness', {
        roleId: selectedRoleObj.value.id,
        name: inputBusiness.value,
      });
      if(inputBusiness.value){
        await fetchBusinesses(inputBusiness.value);
        selectedBusinessDto.value = businessList.value.find(business =>
            (business.name) === inputBusiness.value)
      }
      message.success("新业务【" + selectedRole.value + ":" + inputBusiness.value + "】创建成功");
    } catch (error) {
      message.error('创建业务失败')
      console.error('创建业务失败:', error)
    } finally {
      fetching.value = false
    }
  }
};

// 处理输入框失去焦点时的验证
const handleFailModeBlur = (index: number) => {
  if(failModes && failModes.value[index]){
    console.log(`痛点 ${index + 1}:`, failModes.value[index].modeDesc);
  }
};

const removeFailMode = (index: number) => {
  if (failModes.value.length > 1) {
    failModes.value.splice(index, 1);
  } else {
    message.warning('至少需要保留一个痛点');
  }
};

// 添加痛点
const addFailMode = () => {
  // 检查最后一个输入框是否为空
  const lastFailMode = failModes.value[failModes.value.length - 1];
  if (lastFailMode && lastFailMode.modeDesc?.trim() !== '') {
    failModes.value.push({
      modeDesc: '',
      ctrlPlans: [{ spec: '', capacityId: undefined, frequencyCnList: [], reactionPlanCnList: [] }],
      isExpanded: false // 新增的痛点默认折叠
    });
  } else {
    message.warning('请先填写当前痛点描述');
  }
};

// 添加控制计划
const addCtrlPlan = (failModeIndex: number) => {
  const failMode = failModes.value[failModeIndex];
  if(failMode){
    const lastCtrlPlan = failMode.ctrlPlans[failMode.ctrlPlans.length - 1];
    if (lastCtrlPlan && lastCtrlPlan.spec?.trim() !== '') {
      failMode.ctrlPlans.push({
        spec: '',
        capacityId: 2,
        frequencyCnList: [],
        reactionPlanCnList: [],
        capacityDisplay: '一次',
        isCapacityNew: false
      });
    } else {
      message.warning('请先填写当前控制计划');
    }
  }
};

// 删除控制计划
const removeCtrlPlan = (failModeIndex: number, ctrlPlanIndex: number) => {
  const failMode = failModes.value[failModeIndex];
  if (failMode && failMode.ctrlPlans.length > 1) {
    failMode.ctrlPlans.splice(ctrlPlanIndex, 1);
  } else {
    message.warning('至少需要保留一个控制计划');
  }
};

// 在组件挂载时获取控制计划选项
onMounted(() => {
  if (props.mode === 'add') {
    console.log('初始化新增模式');
    fetchCtrlPlanOptions();
  } else {
    console.log('预览模式，获取选项列表以确保显示正常');
    fetchCtrlPlanOptions();
  }
});

const effectiveFrequencyList = computed(() => {
  if (frequencyList.value.length > 0) {
    return frequencyList.value;
  }

  // 如果选项列表为空，但从预览数据中有选中的值，创建一个虚拟选项列表
  if (props.mode === 'preview' && failModes.value.length > 0) {
    const allFrequencies = new Set<string>();
    failModes.value.forEach(fm => {
      fm.ctrlPlans.forEach(cp => {
        cp.frequencyCnList.forEach(freq => {
          if (freq) allFrequencies.add(freq);
        });
      });
    });

    return Array.from(allFrequencies).map((freq, index) => ({
      id: index,
      cnDesc: freq,
      enDesc: freq
    }));
  }

  return [];
});

const effectiveReactionPlanList = computed(() => {
  if (reactionPlanList.value.length > 0) {
    return reactionPlanList.value;
  }

  // 如果选项列表为空，但从预览数据中有选中的值，创建一个虚拟选项列表
  if (props.mode === 'preview' && failModes.value.length > 0) {
    const allReactionPlans = new Set<string>();
    failModes.value.forEach(fm => {
      fm.ctrlPlans.forEach(cp => {
        cp.reactionPlanCnList.forEach(plan => {
          if (plan) allReactionPlans.add(plan);
        });
      });
    });

    return Array.from(allReactionPlans).map((plan, index) => ({
      id: index,
      cnDesc: plan,
      enDesc: plan
    }));
  }

  return [];
});

// 为每个控制计划添加输入值跟踪
const capacityInputs = ref<Map<string, string>>(new Map());

// 获取特定控制计划的输入值
const getCapacityInput = (failModeIndex: number, ctrlIndex: number): string => {
  const key = `${failModeIndex}-${ctrlIndex}`;
  return capacityInputs.value.get(key) || '';
};

// 设置特定控制计划的输入值
const setCapacityInput = (failModeIndex: number, ctrlIndex: number, value: string) => {
  const key = `${failModeIndex}-${ctrlIndex}`;
  if (value) {
    capacityInputs.value.set(key, value);
  } else {
    capacityInputs.value.delete(key);
  }
};

// 计算是否是新容量（类似于角色的实现）
const isCapacityNew = (failModeIndex: number, ctrlIndex: number): boolean => {
  const ctrlPlan = failModes.value[failModeIndex]?.ctrlPlans[ctrlIndex];
  if (!ctrlPlan) return false;

  const inputValue = getCapacityInput(failModeIndex, ctrlIndex);
  const displayValue = ctrlPlan.capacityDisplay;

  if (inputValue) {
    return !capacityList.value.some(capacity => capacity.cnDesc === inputValue);
  }
  if (displayValue) {
    return !capacityList.value.some(capacity => capacity.cnDesc === displayValue);
  }
  return false;
};

// 容量搜索相关函数
const onCapacitySearch = (value: string, failModeIndex: number, ctrlIndex: number) => {
  fetchCapacities(value);
  if (value) {
    setCapacityInput(failModeIndex, ctrlIndex, value);
  }
}

const onCapacityFocus = (failModeIndex: number, ctrlIndex: number) => {
  if (capacityList.value.length === 0) {
    fetchCapacities('');
  }

  // 在focus时，如果当前有capacityId，设置对应的显示值
  const ctrlPlan = failModes.value[failModeIndex]?.ctrlPlans[ctrlIndex];
  if (ctrlPlan && ctrlPlan.capacityId && !ctrlPlan.capacityDisplay) {
    const capacity = capacityList.value.find(cap => cap.id === ctrlPlan.capacityId);
    if (capacity) {
      ctrlPlan.capacityDisplay = capacity.cnDesc;
    }
  }
}

const onCapacityBlur = (failModeIndex: number, ctrlIndex: number) => {
  const ctrlPlan = failModes.value[failModeIndex]?.ctrlPlans[ctrlIndex];
  if (!ctrlPlan) return;

  const inputValue = getCapacityInput(failModeIndex, ctrlIndex);

  // 如果是新容量，将输入值设置为显示值
  if (isCapacityNew(failModeIndex, ctrlIndex) && inputValue) {
    ctrlPlan.capacityDisplay = inputValue;
    ctrlPlan.isCapacityNew = true;
  } else if (ctrlPlan.capacityDisplay) {
    // 检查显示值是否在列表中
    ctrlPlan.isCapacityNew = !capacityList.value.some(capacity => capacity.cnDesc === ctrlPlan.capacityDisplay);
  }
}

const onCapacityChange = (value: any, failModeIndex: number, ctrlIndex: number) => {
  const ctrlPlan = failModes.value[failModeIndex]?.ctrlPlans[ctrlIndex];
  if (!ctrlPlan) return;

  if (value) {
    const selectedCapacity = capacityList.value.find(capacity => capacity.cnDesc === value);
    if (selectedCapacity) {
      // 选择了现有容量
      ctrlPlan.capacityId = selectedCapacity.id;
      ctrlPlan.isCapacityNew = false;
      setCapacityInput(failModeIndex, ctrlIndex, ''); // 清空输入值
    } else {
      // 输入了新容量
      ctrlPlan.capacityId = undefined;
      ctrlPlan.isCapacityNew = true;
      setCapacityInput(failModeIndex, ctrlIndex, value);
    }
  } else {
    // 清空了选择
    ctrlPlan.capacityId = undefined;
    ctrlPlan.capacityDisplay = undefined;
    ctrlPlan.isCapacityNew = false;
    setCapacityInput(failModeIndex, ctrlIndex, '');
  }
}

// 修改获取容量列表的函数
const fetchCapacities = async (keyword: string) => {
  try {
    fetching.value = true;
    const response = await api.get('/ctrlPlan/cpCapacity', {
      params: { keyword }
    });
    capacityList.value = response.data;
  } catch (error) {
    message.error('获取容量列表失败');
    console.error('获取容量列表失败:', error);
  } finally {
    fetching.value = false;
  }
}
// 处理新容量创建
const handleNewCapacities = async () => {
  const newCapacities: {name: string, ctrlPlans: any[]}[] = [];

  // 收集所有新容量及其对应的控制计划
  failModes.value.forEach((failMode, failModeIndex) => {
    failMode.ctrlPlans.forEach((ctrlPlan, ctrlIndex) => {
      if (ctrlPlan.isCapacityNew) {
        const inputValue = getCapacityInput(failModeIndex, ctrlIndex);
        const capacityName = inputValue || ctrlPlan.capacityDisplay;

        if (capacityName) {
          // 检查是否已经收集过相同名称的容量
          const existing = newCapacities.find(cap => cap.name === capacityName);
          if (existing) {
            existing.ctrlPlans.push({failModeIndex, ctrlIndex});
          } else {
            newCapacities.push({
              name: capacityName,
              ctrlPlans: [{failModeIndex, ctrlIndex}]
            });
          }
        }
      }
    });
  });

  // 创建新容量
  for (const capacityData of newCapacities) {
    try {
      fetching.value = true;
      const response = await api.post('/ctrlPlan/cpCapacity', {
        cnDesc: capacityData.name,
        enDesc: capacityData.name
      });

      // 更新所有使用该新容量的控制计划
      capacityData.ctrlPlans.forEach(({failModeIndex, ctrlIndex}) => {
        const ctrlPlan = failModes.value[failModeIndex]?.ctrlPlans[ctrlIndex];
        if (ctrlPlan) {
          ctrlPlan.capacityId = response.data.id; // 确保 capacityId 被正确设置
          ctrlPlan.isCapacityNew = false;
          setCapacityInput(failModeIndex, ctrlIndex, ''); // 清空输入值
        }
      });

      message.success(`新容量【${capacityData.name}】创建成功`);
    } catch (error) {
      message.error(`创建容量【${capacityData.name}】失败`);
      console.error('创建容量失败:', error);
    } finally {
      fetching.value = false;
    }
  }
};

</script>